#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称: privacy_api.py
完整存储路径: backend/api/miniprogram/privacy_api.py
功能说明:
    微信小程序隐私设置API接口，支持：
    - 隐私设置的获取和更新
    - 强制性文档（隐私政策、用户协议）的获取和确认
    - 用户首次登录的文档确认流程
    
路由说明:
    - GET /api/miniprogram/user/privacy/settings - 获取隐私设置
    - POST /api/miniprogram/user/privacy/settings - 更新隐私设置
    - GET /api/miniprogram/user/privacy/documents - 获取需要确认的文档
    - POST /api/miniprogram/user/privacy/agreements - 确认文档
    - GET /api/miniprogram/user/privacy/check-agreement - 检查用户协议确认状态
"""

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime
from backend.models.document import Document, DocumentType, DocumentStatus, UserDocumentAgreement, UserPrivacySetting
from backend.models.user import User
from backend.infrastructure.database import db
from backend.services.unified_log_service import log_service
from sqlalchemy import and_
from . import miniprogram_bp

@miniprogram_bp.route('/user/privacy/settings', methods=['GET'])
@jwt_required()
def get_privacy_settings():
    """获取用户隐私设置"""
    try:
        current_user_id = get_jwt_identity()
        
        # 查找用户的隐私设置
        privacy_setting = UserPrivacySetting.query.filter_by(user_id=current_user_id).first()
        
        # 如果不存在，创建默认设置
        if not privacy_setting:
            privacy_setting = UserPrivacySetting(
                user_id=current_user_id,
                data_collection=True,
                personalized_recommend=True,
                behavior_analysis=False,
                location_services=False,
                third_party_share=False,
                marketing_messages=True,
                data_retention='2years'
            )
            db.session.add(privacy_setting)
            db.session.commit()
        
        return jsonify({
            'success': True,
            'data': privacy_setting.to_dict()
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取隐私设置失败: {str(e)}'
        }), 500

@miniprogram_bp.route('/user/privacy/settings', methods=['POST'])
@jwt_required()
def update_privacy_settings():
    """更新用户隐私设置"""
    try:
        current_user_id = get_jwt_identity()
        data = request.get_json()
        
        # 查找或创建用户的隐私设置
        privacy_setting = UserPrivacySetting.query.filter_by(user_id=current_user_id).first()
        if not privacy_setting:
            privacy_setting = UserPrivacySetting(user_id=current_user_id)
            db.session.add(privacy_setting)
        
        # 更新设置项
        if 'data_collection' in data:
            privacy_setting.data_collection = data['data_collection']
        if 'personalized_recommend' in data:
            privacy_setting.personalized_recommend = data['personalized_recommend']
        if 'behavior_analysis' in data:
            privacy_setting.behavior_analysis = data['behavior_analysis']
        if 'location_services' in data:
            privacy_setting.location_services = data['location_services']
        if 'third_party_share' in data:
            privacy_setting.third_party_share = data['third_party_share']
        if 'marketing_messages' in data:
            privacy_setting.marketing_messages = data['marketing_messages']
        if 'data_retention' in data:
            privacy_setting.data_retention = data['data_retention']
        
        privacy_setting.updated_at = datetime.utcnow()
        
        db.session.commit()
        
        # 记录操作日志
        log_service.log_operation(
            user_id=current_user_id,
            action='UPDATE',
            table_name='user_privacy_settings',
            record_id=privacy_setting.id,
            details='更新隐私设置'
        )
        
        return jsonify({
            'success': True,
            'data': privacy_setting.to_dict(),
            'message': '隐私设置更新成功'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'更新隐私设置失败: {str(e)}'
        }), 500

@miniprogram_bp.route('/user/privacy/documents', methods=['GET'])
@jwt_required()
def get_mandatory_documents():
    """获取需要用户确认的强制性文档（隐私政策、用户协议）"""
    try:
        current_user_id = get_jwt_identity()
        
        # 获取已发布的强制性文档
        mandatory_docs = Document.query.filter(
            and_(
                Document.is_mandatory == True,
                Document.status == DocumentStatus.PUBLISHED,
                Document.effective_date <= datetime.utcnow()
            )
        ).all()
        
        # 检查用户是否已确认最新版本
        documents_to_confirm = []
        for doc in mandatory_docs:
            # 查找用户对该文档的最新确认记录
            latest_agreement = UserDocumentAgreement.query.filter_by(
                user_id=current_user_id,
                document_id=doc.id
            ).order_by(UserDocumentAgreement.agreed_at.desc()).first()
            
            # 如果没有确认记录，或确认的版本不是当前版本，则需要确认
            if not latest_agreement or latest_agreement.document_version != doc.version:
                documents_to_confirm.append({
                    'id': doc.id,
                    'title': doc.title,
                    'document_type': doc.document_type.value,
                    'content': doc.content,
                    'version': doc.version,
                    'effective_date': doc.effective_date.isoformat() if doc.effective_date else None
                })
        
        return jsonify({
            'success': True,
            'data': {
                'documents': documents_to_confirm,
                'needs_confirmation': len(documents_to_confirm) > 0
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取文档失败: {str(e)}'
        }), 500

@miniprogram_bp.route('/user/privacy/agreements', methods=['POST'])
@jwt_required()
def confirm_documents():
    """用户确认文档（隐私政策、用户协议）"""
    try:
        current_user_id = get_jwt_identity()
        data = request.get_json()
        
        document_ids = data.get('document_ids', [])
        if not document_ids:
            return jsonify({
                'success': False,
                'message': '请选择要确认的文档'
            }), 400
        
        # 获取客户端IP和User-Agent
        ip_address = request.headers.get('X-Forwarded-For', request.remote_addr)
        user_agent = request.headers.get('User-Agent', '')
        
        confirmed_documents = []
        
        for doc_id in document_ids:
            # 获取文档信息
            document = Document.query.get(doc_id)
            if not document or document.status != DocumentStatus.PUBLISHED:
                continue
            
            # 检查是否已经确认过相同版本
            existing_agreement = UserDocumentAgreement.query.filter_by(
                user_id=current_user_id,
                document_id=doc_id,
                document_version=document.version
            ).first()
            
            if existing_agreement:
                continue  # 已经确认过，跳过
            
            # 创建确认记录
            agreement = UserDocumentAgreement(
                user_id=current_user_id,
                document_id=doc_id,
                document_version=document.version,
                agreed_at=datetime.utcnow(),
                ip_address=ip_address,
                user_agent=user_agent
            )
            
            db.session.add(agreement)
            confirmed_documents.append({
                'document_id': doc_id,
                'title': document.title,
                'version': document.version
            })
        
        db.session.commit()
        
        # 记录操作日志
        log_service.log_operation(
            user_id=current_user_id,
            action='CONFIRM',
            table_name='user_document_agreements',
            record_id=None,
            details=f'确认文档: {[doc["title"] for doc in confirmed_documents]}'
        )
        
        return jsonify({
            'success': True,
            'data': {
                'confirmed_documents': confirmed_documents
            },
            'message': '文档确认成功'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'确认文档失败: {str(e)}'
        }), 500

@miniprogram_bp.route('/user/privacy/check-agreement', methods=['GET'])
@jwt_required()
def check_agreement_status():
    """检查用户是否已确认所有必要的文档"""
    try:
        current_user_id = get_jwt_identity()
        
        # 获取所有强制性文档
        mandatory_docs = Document.query.filter(
            and_(
                Document.is_mandatory == True,
                Document.status == DocumentStatus.PUBLISHED,
                Document.effective_date <= datetime.utcnow()
            )
        ).all()
        
        all_confirmed = True
        pending_documents = []
        
        for doc in mandatory_docs:
            # 检查用户是否已确认最新版本
            latest_agreement = UserDocumentAgreement.query.filter_by(
                user_id=current_user_id,
                document_id=doc.id,
                document_version=doc.version
            ).first()
            
            if not latest_agreement:
                all_confirmed = False
                pending_documents.append({
                    'id': doc.id,
                    'title': doc.title,
                    'document_type': doc.document_type.value,
                    'version': doc.version
                })
        
        return jsonify({
            'success': True,
            'data': {
                'all_confirmed': all_confirmed,
                'pending_documents': pending_documents,
                'can_use_service': all_confirmed  # 只有确认所有文档才能使用服务
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'检查确认状态失败: {str(e)}'
        }), 500

@miniprogram_bp.route('/user/privacy/policy', methods=['GET'])
def get_privacy_policy():
    """获取最新的隐私政策（无需登录）"""
    try:
        privacy_policy = Document.query.filter(
            and_(
                Document.document_type == DocumentType.PRIVACY_POLICY,
                Document.status == DocumentStatus.PUBLISHED,
                Document.effective_date <= datetime.utcnow()
            )
        ).order_by(Document.published_at.desc()).first()
        
        if not privacy_policy:
            return jsonify({
                'success': False,
                'message': '未找到隐私政策'
            }), 404
        
        return jsonify({
            'success': True,
            'data': {
                'id': privacy_policy.id,
                'title': privacy_policy.title,
                'content': privacy_policy.content,
                'version': privacy_policy.version,
                'effective_date': privacy_policy.effective_date.isoformat() if privacy_policy.effective_date else None,
                'updated_at': privacy_policy.updated_at.isoformat() if privacy_policy.updated_at else None
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取隐私政策失败: {str(e)}'
        }), 500

@miniprogram_bp.route('/user/privacy/agreement', methods=['GET'])
def get_user_agreement():
    """获取最新的用户协议（无需登录）"""
    try:
        user_agreement = Document.query.filter(
            and_(
                Document.document_type == DocumentType.USER_AGREEMENT,
                Document.status == DocumentStatus.PUBLISHED,
                Document.effective_date <= datetime.utcnow()
            )
        ).order_by(Document.published_at.desc()).first()
        
        if not user_agreement:
            return jsonify({
                'success': False,
                'message': '未找到用户协议'
            }), 404
        
        return jsonify({
            'success': True,
            'data': {
                'id': user_agreement.id,
                'title': user_agreement.title,
                'content': user_agreement.content,
                'version': user_agreement.version,
                'effective_date': user_agreement.effective_date.isoformat() if user_agreement.effective_date else None,
                'updated_at': user_agreement.updated_at.isoformat() if user_agreement.updated_at else None
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取用户协议失败: {str(e)}'
        }), 500
